package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.consts.RabbitConst;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.model.mq.to.order.OrderCreateMsg;
import com.atguigu.gmall.order.biz.OrderService;
import com.atguigu.gmall.rabbit.component.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 **/
@Service
@Slf4j
public class OrderClosedListener {

    @Autowired
    OrderService orderService;
    @Autowired
    RabbitService rabbitService;

    /**
     * 监听死信队列
     *
     */
    @RabbitListener(queues = RabbitConst.QUEUE_ORDER_DEAD)
    public void handle(Message message, Channel channel) throws IOException {
        MessageProperties messageProperties = message.getMessageProperties();
        String msgStr = new String(message.getBody());
        OrderCreateMsg msg = JsonUtil.strToObj(msgStr, OrderCreateMsg.class);
        try {
            log.info("正在关单中，消息内容：{}", msgStr);
            //处理业务逻辑，关单
            orderService.closeOrder(msg);
            //手动确认
            channel.basicAck(messageProperties.getDeliveryTag(), false);
        } catch (Exception e) {
            //重试
            log.info("关单失败,消息内容：{}",msgStr);
            rabbitService.retry(message,channel,5);
        }
    }
}
